import axios from "axios";
import {BEARER, TOKEN_NAME} from "./constant.js";
import {confirmMessage} from "./message.js";


axios.defaults.baseURL = "http://localhost:8088";
// get请求
export const doGet = (url, params) => {
  return axios({
      method:'GET',
      url,
      params,
  });
};
// post请求
export const doPost = (url, data) => {
  return axios({
      method:'POST',
      url,
      data
  });
};
// put请求
export const doPut = (url, data) => {
  return axios({
      method:'PUT',
      url,
      data
  });
};
// delete请求
export const doDelete = (url, data) => {
  return axios({
      method:'DELETE',
      url,
      data
  });
};

/**
 * 下载请求
 * @param url
 * @param params
 * @returns {Promise<AxiosResponse<any>> | *}
 */
export const doDownload = (url, params) => {
    return axios({
        url: url,   // 请求接口地址
        method: 'GET',  // 请求方式
        params: params,   // `data` 是作为请求体被发送的数据
        responseType: 'blob'
    });
}
//请求拦截器
axios.interceptors.request.use(
    function (config){
        //在发送请求之前做些什么
        // 请求头添加token
        //本地获取token
        let token = localStorage.getItem(TOKEN_NAME);
        // 判断token是否存在
        if(token){
            //请求头添加token
            config.headers.Authorization = BEARER+token;
            // 本地有token值，说明用户选择了“记住我”
            config.headers['sss'] = true;
        }else {
            // 本地没有token值，说明用户没有选择“记住我”
            token  = sessionStorage.getItem(TOKEN_NAME);

                //请求头添加token 会话session
                config.headers.Authorization = BEARER+token;
            // 本地没有token值，说明用户没有选择了“记住我”
            config.headers['sss'] = false;
        }

        return config;
    },function (error){
        return Promise.reject(error);
    }
);
//响应拦截器
axios.interceptors.response.use(
    function (response){
        //判断响应码
        if(response.data.code > 900){
            confirmMessage ('登录过期,请重新登录!')
                .then(()=>{
                    // 清除token
                    localStorage.removeItem(TOKEN_NAME);
                    sessionStorage.removeItem(TOKEN_NAME);
                    // 跳转到登录页
                    window.location.href = '/';
                })
                .catch(()=>{
                    // 清除token
                    localStorage.removeItem(TOKEN_NAME);
                    sessionStorage.removeItem(TOKEN_NAME);
                    // 跳转到登录页
                    window.location.href = '/';
                });
        }
        return response;
    },function (error){
        return Promise.reject(error);
    }
);
//
